
package com.monlyu.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageUtils {

    /** 水印类型 */
    public static enum WATER_MARK_TYPE {
        TEXT, IMAGE
    }

    public static enum ZOOM {
        ZOOM_OUT, /* 放大 */
        ZOOM_IN
        /* 缩小 */
    };

    /**
     * 缩放图像
     */
    public static void scale(String srcImageFile, String result, int scale, Enum<ZOOM> type){
        try {
            BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
            int width = src.getWidth(); // 得到源图宽
            int height = src.getHeight(); // 得到源图长
            if (type == ZOOM.ZOOM_OUT) {
                width = width * scale;
                height = height * scale;
            } else {
                width = width / scale;
                height = height / scale;
            }
            toSize(srcImageFile, result, width, height);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 同步到好大的图片
    public static void scaleSysnc(String srcImageFile, String result, int descWidth){
        try {
            BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
            int width = src.getWidth(); // 得到源图宽
            int height = src.getHeight(); // 得到源图长
            toSize(srcImageFile, result, descWidth, (int) (descWidth / ((float) width / height)));
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param src 源文件
     * @param desc 目标文件
     * @param width 宽度
     * @param height 高度
     */
    public static void toSize(String src, String desc, int width, int height){
        try {
            BufferedImage srcImg = ImageIO.read(new File(src)); // 读入文件
            Image image = srcImg.getScaledInstance(width, height, Image.SCALE_DEFAULT);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            ImageIO.write(tag, "JPEG", new File(desc));// 输出到文件流
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 图像切割
     * 
     * @param srcImageFile 源图像地址
     * @param descDir 切片目标文件夹
     * @param destWidth 目标切片宽度
     * @param destHeight 目标切片高度
     */
    public static void cut(String srcImageFile, String descDir, int destWidth, int destHeight){
        try {
            Image img;
            ImageFilter cropFilter;
            // 读取源图像
            BufferedImage bi = ImageIO.read(new File(srcImageFile));
            int srcWidth = bi.getHeight(); // 源图宽度
            int srcHeight = bi.getWidth(); // 源图高度
            if (srcWidth > destWidth && srcHeight > destHeight) {
                Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
                destWidth = 200; // 切片宽度
                destHeight = 150; // 切片高度
                int cols = 0; // 切片横向数量
                int rows = 0; // 切片纵向数量
                // 计算切片的横向和纵向数量
                if (srcWidth % destWidth == 0) {
                    cols = srcWidth / destWidth;
                } else {
                    cols = (int) Math.floor(srcWidth / destWidth) + 1;
                }
                if (srcHeight % destHeight == 0) {
                    rows = srcHeight / destHeight;
                } else {
                    rows = (int) Math.floor(srcHeight / destHeight) + 1;
                }
                // 循环建立切片
                // 改进的想法:是否可用多线程加快切割速度
                for (int i = 0; i < rows; i++) {
                    for (int j = 0; j < cols; j++) {
                        // 四个参数分别为图像起点坐标和宽高
                        // 即: CropImageFilter(int x,int y,int width,int height)
                        cropFilter = new CropImageFilter(j * 200, i * 150, destWidth, destHeight);
                        img = Toolkit.getDefaultToolkit().createImage(
                            new FilteredImageSource(image.getSource(), cropFilter));
                        BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
                        Graphics g = tag.getGraphics();
                        g.drawImage(img, 0, 0, null); // 绘制缩小后的图
                        g.dispose();
                        // 输出为文件
                        ImageIO.write(tag, "JPEG", new File(descDir + "pre_map_" + i + "_" + j + ".jpg"));
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** */
    /**
     * 图像类型转换 GIF->JPG GIF->PNG PNG->JPG PNG->GIF(X)
     */
    public static void convert(String source, String result){
        try {
            File f = new File(source);
            f.canRead();
            f.canWrite();
            BufferedImage src = ImageIO.read(f);
            ImageIO.write(src, "JPG", new File(result));
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /** */
    /**
     * 彩色转为黑白
     * 
     * @param source
     * @param result
     */
    public static void gray(String source, String result){
        try {
            BufferedImage src = ImageIO.read(new File(source));
            ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
            ColorConvertOp op = new ColorConvertOp(cs, null);
            src = op.filter(src, null);
            ImageIO.write(src, "JPEG", new File(result));
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
     * 构造函数1，打印文字水印图片
     * @param pressText --文字
     * @param targetImg -- 目标图片
     * @param fontName -- 字体名
     * @param fontStyle -- 字体样式
     * @param color -- 字体颜色
     * @param fontSize -- 字体大小
     * @param x -- 右下角的偏移量
     * @param y
     * Such As:new waterTextImage("spy", "D:\\Documents\\No.jpg", "Monospace", Font.TRUETYPE_FONT,
     * Color.GREEN, 46, 50, 40);
     */
    public static void waterTextImage(
                                      String text,
                                      String src,
                                      String desc,
                                      String font,
                                      int fontStyle,
                                      Color color,
                                      int fontSize){
        try {
            File file = new File(src);
            Image targetImg = ImageIO.read(file);
            int width = targetImg.getWidth(null);
            int height = targetImg.getHeight(null);
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.createGraphics();
            g.drawImage(targetImg, 0, 0, width, height, null);
            g.setColor(color);
            g.setFont(new Font(font, fontStyle, fontSize));
            g.drawString(text, width / 2, height / 2);
            g.dispose(); // 输出图像
            FileOutputStream out = new FileOutputStream(desc);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(image);
            out.close();
        }
        catch (IOException ex) {}
    }

    /*
     * 构造函数2，打印图片水印图片
     * @param pressImg --被当做水印的图片
     * @param targetImg -- 目标图片
     * @param x -- 右下角的偏移量
     * @param y
     * Such As:new ImageWaterMark("D:\\Documents\\no5.jpg","E:\\software\\picture\\Win7_21.jpg",
     * 200, 100);
     */
    public static void imageWaterMark(String pressImg, String targetImg, int x, int y){
        try {
            File _file = new File(targetImg);
            Image src = ImageIO.read(_file);
            int wideth = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.createGraphics();
            g.drawImage(src, 0, 0, wideth, height, null);
            // 水印文件
            File _filebiao = new File(pressImg);
            Image src_biao = ImageIO.read(_filebiao);
            int wideth_biao = src_biao.getWidth(null);
            int height_biao = src_biao.getHeight(null);
            g.drawImage(src_biao, wideth - wideth_biao - x, height - height_biao - y, wideth_biao, height_biao, null);
            g.dispose();
            // 输出图像
            FileOutputStream out = new FileOutputStream(targetImg);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(image);
            out.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        scaleSysnc("/Users/monlyu/Resources/Pictures/2008-07-01(毕业照)/100_5081.JPG", "/Users/monlyu/Desktop/aa.jpg", 780);
    }
}
